<template>
  <ul class="footer">
    <li :class="{ active: $route.path === '/index' }" @click="toPage('/index')">
      <i class="fa fa-home"></i>
      <p>主页</p>
    </li>
    <li :class="{ active: $route.path === '/message' }" @click="toPage('/message')">
      <div class="icon-wrapper">
        <i class="fa fa-comments"></i>
        <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
      </div>
      <p>消息</p>
    </li>
    <li :class="{ active: $route.path === '/cart' }" @click="toPage('/cart')">
      <i class="fa fa-shopping-cart"></i>
      <p>购物车</p>
    </li>
    <li :class="{ active: $route.path === '/profile' }" @click="toPage('/profile')">
      <i class="fa fa-user"></i>
      <p>我的</p>
    </li>
  </ul>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserInfoStore } from '../stores/user';
import { getMessageList } from '../api/message';

const router = useRouter();
const userStore = useUserInfoStore();
const unreadCount = ref(0);

// 获取未读消息数量
const getUnreadCount = async () => {
  try {
    if (!userStore.userInfo) return;
    
    const res = await getMessageList(userStore.userInfo.id);
    if (res.code === 0) {
      // 计算未读消息数量
      const count = res.data.reduce((acc, msg) => {
        if (msg.status === 0 && msg.senderId !== userStore.userInfo.id) {
          return acc + 1;
        }
        return acc;
      }, 0);
      unreadCount.value = count;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
};

// 监听路由变化，更新未读消息数量
watch(() => router.currentRoute.value.path, (newPath) => {
  if (newPath !== '/message') {
    getUnreadCount();
  }
});

onMounted(() => {
  getUnreadCount();
});

const toPage = (path) => {
  router.push(path);
};
</script>

<style scoped>
.footer {
  width: 100%;
  height: 14vw;
  background-color: #fff;
  border-top: solid 1px #f1ebeb;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 1000;
}

.footer li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  cursor: pointer;
  user-select: none;
}

.icon-wrapper {
  position: relative;
  display: inline-block;
}

.unread-badge {
  position: absolute;
  top: -1.5vw;
  right: -1.5vw;
  background-color: #ff4646;
  color: white;
  border-radius: 3vw;
  padding: 0.3vw 1vw;
  font-size: 2.2vw;
  min-width: 3vw;
  height: 3vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer li p {
  font-size: 2.8vw;
  margin-top: 0.5vw;
}

.footer li i {
  font-size: 5vw;
}

.footer li.active {
  color: #ff7043;
}
</style>